<template>
  <view class="c-pd">
    <view v-if="state.historyReportList.length > 0">
      <van-cell-group inset title="历史上报">
        <van-cell :title="'地址：' + item.site" :value="item.createDate" v-for="(item, index) in state.historyReportList" :key="index" />
      </van-cell-group>
    </view>
    <view v-if="state.alarmId">
      <van-cell-group inset title="火灾信息">
        <van-cell :title="state.alarmAddress" :value="state.alarmDate" />
      </van-cell-group>
    </view>
    <view class="title c-text-14"> 火情上报 </view>
    <view>
      <SelectLocation ref="childComp" :isGetUserAddress="false" @returnData="setLocation" @clearData="clearLocation" />
    </view>
    <view class="mt-3">
      <van-cell-group inset>
        <van-cell title="详细位置" use-label-slot>
          <view slot="label">
            <van-field
              custom-style="border: 1px solid #ddd; border-radius:16rpx"
              :value="state.site"
              type="textarea"
              placeholder="请输入详细位置"
              :border="false"
              :autosize="{ maxHeight: 200, minHeight: 100 }"
              @change="
                (e: any) => {
                  state.site = e.detail;
                }
              "
            />
          </view>
        </van-cell>
      </van-cell-group>
    </view>
    <view class="mt-3">
      <van-cell-group inset>
        <van-cell title="火情描述" use-label-slot>
          <view slot="label">
            <van-field
              custom-style="border: 1px solid #ddd; border-radius:16rpx"
              :value="state.fireDesc"
              type="textarea"
              placeholder="请填写火情详细情况（如燃烧原因、火势大小等）"
              :border="false"
              :autosize="{ maxHeight: 200, minHeight: 100 }"
              @change="
                (e: any) => {
                  state.fireDesc = e.detail;
                }
              "
            />
          </view>
        </van-cell>
      </van-cell-group>
    </view>
    <view class="mt-3">
      <UploadFile @clearUrl="clearUrl" @returnUrl="setVideoUrl" title="上传视频"></UploadFile>
    </view>
    <view class="mt-3" :style="{ marginBottom: `${store.$state.systemInfo.safeAreaInsets!.bottom}px` }">
      <van-button type="primary" block @click="handleSendReport">上报</van-button>
    </view>
    <van-dialog use-slot title="请选择一项报警" confirm-button-text="确认" confirm-button-color="#ffc330" :show="state.popupShow" :before-close="onBeforeClose">
      <view class="dialog_box">
        <view
          v-for="(item, index) in state.fireInformationInfoList"
          :key="index"
          :class="{
            'cell_box_select mb-3': item.alarmId === state.alarmId,
            'mb-3': true,
          }"
          @click="
            state.alarmId = item.alarmId;
            state.alarmDate = item.createDate;
            state.alarmAddress = item.address;
          "
        >
          <van-cell-group :key="index" inset>
            <van-cell title="火灾地址" :label="item.address" />
            <van-cell title="火灾时间" :label="item.createDate" />
          </van-cell-group>
        </view>
      </view>
    </van-dialog>
  </view>
</template>

<script setup lang="ts">
import { useAppStore } from '@/store';
import UploadFile from '../component/UploadFile.vue';
import SelectLocation from '../component/SelectLocation.vue';
import useModal from '@/hooks/useModal';
import useToast from '@/hooks/useToast';
import HomeRequest from '@/request/homeRequest';
import { navigate } from '@/utils/navigate';

interface IState {
  alarmId: number;
  alarmAddress: string;
  alarmDate: string;
  buildId: number;
  buildName: string;
  floorId: number;
  floorName: string;
  houseNumber: string;
  houseNumberId: number;
  site: string;
  fireDesc: string;
  fireVideos: string;
  unitId: number;
  unitName: string;
  beeperId: number;
  fireInformationInfoList: IGetAlarmRecord[];
  historyReportList: IFireHistoryReport[];
  popupShow: boolean;
}

const store = useAppStore();

const state = reactive<IState>({
  beeperId: store.$state.beeperId,
  alarmId: 0,
  alarmAddress: '',
  alarmDate: '',
  buildId: 0,
  buildName: '',
  floorId: 0,
  floorName: '',
  houseNumber: '',
  houseNumberId: 0,
  site: '',
  fireDesc: '',
  fireVideos: '',
  unitId: 0,
  unitName: '',
  fireInformationInfoList: [],
  historyReportList: [],
  popupShow: false,
});

const { showModal } = useModal();

const { showToast } = useToast();

const childComp = ref();

onLoad(() => {
  getFireInformation();
});

//清空楼栋层
const clearLocation = () => {
  Object.assign(state, {
    buildId: 0,
    buildName: '',
    unitId: 0,
    unitName: '',
    floorId: 0,
    floorName: '',
    houseNumberId: '',
    houseNumber: '',
  });
};

//设置楼栋层
const setLocation = (payload: { item: IBuildingTreeRes[]; isUpload: boolean }) => {
  if (payload.item.length >= 1 && payload.item[0].id) {
    state.buildId = Number(payload.item[0].id);
    state.buildName = payload.item[0].name;
  }
  if (payload.item.length >= 2 && payload.item[1].id) {
    state.unitId = Number(payload.item[1].id);
    state.unitName = payload.item[1].name;
  }
  if (payload.item.length >= 3 && payload.item[2].id) {
    state.floorId = Number(payload.item[2].id);
    state.floorName = payload.item[2].name;
  }
  if (payload.item.length >= 4 && payload.item[3].id) {
    state.houseNumberId = Number(payload.item[3].id);
    state.houseNumber = payload.item[3].name;
  }
};

//清空视频
const clearUrl = () => {
  state.fireVideos = '';
};

//获取视频地址
const setVideoUrl = ({ url }: { url: string }) => {
  state.fireVideos = url;
};

const handleSendReport = () => {
  const { alarmId, buildId, buildName, floorId, floorName, houseNumber, houseNumberId, site, fireDesc, fireVideos, unitId, unitName } = state;
  let params: any = { alarmId, buildId, buildName, floorId, floorName, houseNumber, houseNumberId, site, fireDesc, fireVideos, unitId, unitName, hasLoading: true };
  if (!buildName && !site) {
    showModal('所在楼层或详细位置必须填写一个');
    return false;
  }
  if (!fireDesc) {
    showModal('请填写火情描述');
    return false;
  }
  HomeRequest.SendFireReport(params).then((res) => {
    if (res.status === 0) {
      showToast('上报成功', 'success');
      setTimeout(() => {
        navigate({ url: '', type: 'navigateBack' });
      }, 1000);
    }
  });
};

const getFireInformation = () => {
  HomeRequest.GetAlarmRecord({
    hasLoading: true,
    beeperId: state.beeperId,
  }).then((res) => {
    if (res.status === 0) {
      state.fireInformationInfoList = res.data;
      if (state.fireInformationInfoList.length >= 1) {
        state.popupShow = true;
      } else {
        showModal('24小时内无火灾报警，无需上报', {
          showCancel: false,
          success: () => {
            navigate({ url: '', type: 'navigateBack' });
          },
        });
      }
    }
  });
};

const getHistoryReport = () => {
  HomeRequest.GetFireHistoryReport({
    hasLoading: true,
    alarmId: state.alarmId,
  }).then((res) => {
    if (res.data.length > 0) {
      state.historyReportList = res.data.map((item) => {
        return {
          ...item,
          site: item.buildName + item.unitName + item.floorName + item.houseNumber + item.site,
        };
      });
    }
  });
};

const onBeforeClose = (action: string) => {
  if (action === 'confirm') {
    if (!state.alarmId) {
      showModal('请选择一项火灾信息');
      return false;
    } else {
      getHistoryReport();
      state.popupShow = false;
      return true;
    }
  } else {
    return true;
  }
};
</script>

<style scoped lang="scss">
:deep(.van-panel) {
  border-radius: 16rpx !important;
}

:deep(.van-cell-group__title) {
  padding-left: 0;
}

:deep(.van-dialog__header) {
  padding-top: 24rpx;
  padding-bottom: 24rpx;
}

.dialog_box {
  overflow: auto;
  padding: 24rpx 24rpx 0;
  max-height: 800rpx;
  background: #f3f3f3;
}

.cell_box_select {
  border: 1px solid #ffc330;
  border-radius: 16rpx !important;
}

.title {
  padding: 32rpx 32rpx 16rpx 0;
  box-sizing: border-box;
  color: #969799;
}
</style>
